<?php


namespace apps\marriage\core\service;


use apps\marriage\core\model\UserCheckIn;
use think\Exception;
use vm\com\BaseModel;
use vm\com\BaseService;

class UserCheckInService extends BaseService
{

    /**
     * @inheritDoc
     */
    protected function getModel()
    {
        return new UserCheckIn();
    }

    /**
     * @return BaseService|UserService
     */
    private function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|SiteConfigService
     */
    private function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    public function create(array $data)
    {
        $beginTime = strtotime(date('Ymd') . ' 00:00:00');
        $endTime = strtotime(date('Ymd') . ' 23:59:59');
        if($this->getByLimitTime($data['user_id'], $beginTime, $endTime)) {
            throw new Exception('今日已签到');
        }

        $checkInRewardMin = floatval($this->getSiteConfigService()->getValueByCode('check_in_reward_min')) * 100;
        $checkInRewardMax = floatval($this->getSiteConfigService()->getValueByCode('check_in_reward_max')) * 100;
        $coin = randLimitNumber($checkInRewardMin, $checkInRewardMax) / 100;
        $data['reward_gold_coin'] = $coin;
        $data['dateline'] = time();
        if(parent::create($data)) {
            $this->getUserService()->increaseGoldCoin($data['user_id'], $coin, true, '签到奖励');
        }
        return $coin;
    }

    public function getByLimitTime($userId, $beginTime, $endTime)
    {
        return $this->getModel()->getByLimitTime($userId, $beginTime, $endTime);
    }
}